<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.bpmBizTitle"
                    placeholder="请输入标题"
                    :max-length="255"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="入职人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyId">
                  <select-hr-apply-bill-input
                    :disabled="formDisabled"
                    v-model="model.applyId"
                    @back="selectApply"/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
            <a-form-model-item label="入职单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyUnit">
              <j-select-depart :disabled=formDisabled v-model="model.applyUnit" />
            </a-form-model-item>
          </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="入职部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departmentId">
                  <j-select-depart :disabled="formDisabled" v-model="model.departmentId" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="岗位序列" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="positionCategory">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.positionCategory"
                    dictCode="position_category"
                    placeholder="请选择岗位序列"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="职务级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="positionLevelId">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    placeholder="请选择职务级别"
                    v-model="model.positionLevelId"
                    :dictCode="positionLevelIdDict"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="入职岗位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="positionId">
                  <j-search-select
                    :disabled="formDisabled"
                    v-model="model.positionId"
                    placeholder="请选择入职岗位"
                    :dict="positionIdDict"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="入职类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inductionType">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.inductionType"
                    dictCode="induction_type"
                    placeholder="请选择入职类型"
                    @input="changeSelect" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="this.model.inductionType=='4'">
                <a-form-model-item label="推荐人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="recommendId">
                  <select-user-by-dep
                    :disabled="formDisabled"
                    :multi="false"
                    v-model="model.recommendId" ></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input
                    :disabled="formDisabled"
                    v-model="model.teamId"
                    :tdlx="3"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="试用期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="probationership">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.probationership" dictCode="probationership" placeholder="请选择试用期" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="转正后薪资（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="conversionSalary">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.conversionSalary"
                    @change="inputAmount"
                    placeholder="请输入转正后薪资"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="试用期薪资（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="trialSalary">
                  <!--              <a-input :disabled=formDisabled v-model="model.trialSalary" placeholder="请输入试用期薪资" ></a-input>-->
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.trialSalary"
                    placeholder="请输入试用期薪资"
                    style="width: 100%" />

                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
            <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="feeTeamId">
              <select-team-input
                  :disabled=formDisabled
                  v-model="model.feeTeamId" :tdlx="3"/>
            </a-form-model-item>
          </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="参保单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="insuredUnit">
                  <select-Company-input :disabled="formDisabled" v-model="model.insuredUnit" />
                  <!-- <j-select-depart :disabled=formDisabled v-model="model.insuredUnit" /> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="参保基数（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="insuredBase">
                  <a-input :disabled="formDisabled" v-model="model.insuredBase" placeholder="请输入参保基数" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="工作性质" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workType">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.workType" dictCode="work_type" placeholder="请选择工作性质" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="到岗时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="arrivalTime">
                  <j-date :disabled="formDisabled" placeholder="请选择到岗时间" v-model="model.arrivalTime" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="执业金（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="practicingGold">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.practicingGold"
                    placeholder="请输入执业金"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" v-model="model.remark" rows="4" placeholder="请输入备注" :max-length="500"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachments">
                  <j-upload :disabled="formDisabled" v-model="model.attachments" ></j-upload>
                </a-form-model-item>
              </a-col>
            <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
              <a-button @click="submitForm">提 交</a-button>
            </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpHrInductionBillFormPrint v-if="formBpm" class="print_style" id="hrinductionContent" :formData="model" :formDataHistory="formData"></ErpHrInductionBillFormPrint>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectHrApplyBillInput from '@/views/scy/components/SelectHrApplyBillInput'
import JSearchSelect from '@views/erp/hr/apply/modules/JSearchSelect.vue'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpHrInductionBillFormPrint from './ErpHrInductionBillFormPrint' // 打印组件
export default {
  name: 'ErpHrInductionBillForm',
  components: {
    SelectTeamInput,
    SelectHrApplyBillInput,
    JSearchSelect,
    SelectCompanyInput,
    SelectUserByDep,
    CommonFlowList,
    ErpHrInductionBillFormPrint
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      activeKey: ['1', '2'],
      model: {},
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      positionIdDict: 'sys_position,name,id,del_flag = 0 and audit_status=2 and is_virtual=0',
      positionLevelIdDict: 'erp_org_position_level,level_name,id,del_flag="0" and audit_status="2"',
      validatorRules: {
        bpmBizTitle: [
          { required: true, message: '请输入流程标题!' }
        ],
        positionCategory: [
          { required: true, message: '请选择岗位序列!' }
        ],
        applyId: [
          { required: true, message: '请选择入职人员!' }
          // {validator: (rule, value, callback) => validateDuplicateValue('erp_hr_induction_bill', 'apply_id', value, this.model.id, callback) }
        ],
        applyUnit: [
          { required: true, message: '请选择入职单位!' }
        ],
        trialSalary: [
          { required: false, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        ],
        departmentId: [
          { required: true, message: '请选择入职部门!' }
        ],
        positionId: [
          { required: true, message: '请选择入职岗位!' }
        ],
        positionLevelId: [
          { required: true, message: '请选择职务级别!' }
        ],
        teamId: [
          { required: true, message: '请选择所属团队!' }
        ],
        inductionType: [
          { required: true, message: '请选择入职类型!' }
        ],
        probationership: [
          { required: true, message: '请选择试用期限!' }
        ],
        conversionSalary: [
          { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入转正后薪资!' }
        ],
        feeTeamId: [
        { required: true, message: '请选择费用所属团队!' }
        ],
        insuredUnit: [
          { required: true, message: '请选择参保单位!' }
        ],
        insuredBase: [
          { required: true, message: '请输入参保基数!' }
        ],
        workType: [
          { required: true, message: '请选择工作性质!' }
        ],
        arrivalTime: [
          { required: true, message: '请输入到岗时间!' }
        ]
      },
      url: {
        add: '/api/erp/hr/induction/erpHrInductionBill/add',
        edit: '/api/erp/hr/induction/erpHrInductionBill/edit',
        queryById: '/api/erp/hr/induction/erpHrInductionBill/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  watch: {
    activeKey(key) {
      this.$forceUpdate()
    }
  },
  methods: {
    changeSelect() {
      this.$set(this.model, 'recommendId', null);
    },
    selectApply(data) {
      this.$set(this.model, 'bpmBizTitle', data[0].name);
    },
    inputAmount() {
      let conversionSalary = this.model.conversionSalary;
      if (conversionSalary) {
        this.$set(this.model, 'trialSalary', (conversionSalary * 0.8).toFixed(2))
      } else {
        this.$set(this.model, 'trialSalary', 0)
      }
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },

    submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      httpAction(httpurl, this.model, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable');
        }
      }).catch((error) => {
        that.$emit('unButtonDisable', error);
      }).finally(() => {
        that.confirmLoading = false;
      })
    },

    // 点击打印
    onPrint () {
        let print = new Print({
          el: '#hrinductionContent',
          popTitle: '入职申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
  }
}
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
